package com.yuyou.train.admin.controller;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yuyou.train.admin.service.IAuthUserService;
import com.yuyou.train.admin.service.ICommDataConfigService;
import com.yuyou.train.admin.vo.req.ReqAuthUserAdd;
import com.yuyou.train.admin.vo.req.ReqAuthUserUpdate;
import com.yuyou.train.service.api.admin.dto.AuthUserDTO;
import com.yuyou.train.service.api.admin.entity.AuthUser;
import com.yuyou.train.service.api.admin.entity.CommDataConfig;
import com.yuyou.train.util.bean.LoginRedisObj;
import com.yuyou.train.util.bean.PageParams;
import com.yuyou.train.util.bean.Pagination;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.bean.ReturnResult;
import com.yuyou.train.util.tool.DateUtil;

/**
 * Created by yujin.liu on 2018/1/19.
 */
@Validated
@RestController
@RequestMapping(value="/api/authUser")
public class AuthUserController extends BaseController{

    @Autowired
    private IAuthUserService authUserService;
    
	@Autowired
	private ICommDataConfigService commDataConfigService;


    @ApiOperation(value="查找用户(分页)")
    @RequestMapping(value="/findAuthUserPage", method = { RequestMethod.GET ,RequestMethod.POST })
    public ReturnResult<AuthUserDTO> findAuthUserPage(@Validated @ModelAttribute PageParams pageParams,
                                                      @RequestParam(value = "username", required = false) String username,
                                                      @RequestParam(value = "status", required = false)Integer status,
                                                      @RequestParam(value = "areaId", required = false)String areaId){
        Map<String, Object> conditions = new HashMap<>();
        Pagination<AuthUserDTO> queryPgn = new Pagination<>();
        if(!StringUtils.isEmpty(username)){
            conditions.put("username", username.trim());
        }
        if(null != status){
            conditions.put("status", status);
        }
        if(!StringUtils.isEmpty(areaId)){
            conditions.put("areaId", areaId);
        }

        queryPgn.setConditions(conditions);
        queryPgn.setPageParams(pageParams);
        int total = authUserService.findAuthUserPageCount(queryPgn);
        queryPgn.setTotal(total);
        queryPgn.toBePage();
        if(total > 0){
            queryPgn.setTotal(total);
            List<AuthUserDTO> list = authUserService.findAuthUserPageList(queryPgn);
            queryPgn.setList(list);
        }

        return ReturnResult.success(queryPgn);
    }

    @ApiOperation(value="查找单个用户")
    @RequestMapping(value="/findAuthUser", method = { RequestMethod.GET ,RequestMethod.POST })
    public ReturnResult<AuthUserDTO> findAuthUser(@NotBlank(message="id不能为空") @RequestParam(value = "id")String id){

        AuthUserDTO authUserDTO = authUserService.findAuthUser(id);

        return ReturnResult.success(authUserDTO);
    }

    @ApiOperation(value="添加用户")
    @RequestMapping(value="/addAuthUser", method = RequestMethod.POST )
    public ReturnResult<ResBoolSimpleInfo> addAuthUser(@Validated @ModelAttribute ReqAuthUserAdd reqAuthUserAdd){

        ResBoolSimpleInfo res = authUserService.insertAuthUser(reqAuthUserAdd);

        return ReturnResult.success(res);
    }

    @ApiOperation(value="更新用户")
    @RequestMapping(value="/updateAuthUser", method = { RequestMethod.GET ,RequestMethod.POST })
    public ReturnResult<ResBoolSimpleInfo> updateAuthUser(@Validated @ModelAttribute ReqAuthUserUpdate reqAuthUserUpdate){

        ResBoolSimpleInfo res = authUserService.updateAuthUser(reqAuthUserUpdate);
        return ReturnResult.success(res);
    }


    @ApiOperation(value="用户状态更改")
    @RequestMapping(value="/updateAuthUserStatus", method = { RequestMethod.GET ,RequestMethod.POST })
    public ReturnResult updateAuthUser(@NotBlank(message="用户id不能为空") @RequestParam(value = "id") String id,
                                       @NotNull(message="状态status不能为空") @RequestParam(value = "status") Integer status){

        AuthUser authUser = new AuthUser();
        authUser.setId(id);
        authUser.setStatus(status);
        authUser.setUpdateTime(DateUtil.now());
        authUserService.updateByPrimaryKeySelective(authUser);

        return ReturnResult.success(authUser);
    }


    @ApiOperation(value="删除用户")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "角色id", paramType="query", required = true)})
    @RequestMapping(value="/deleteAuthUser", method = { RequestMethod.GET ,RequestMethod.POST })
    public ReturnResult<Void> deleteAuthUser(@NotBlank(message="id不能为空") String id){

        authUserService.deleteAuthUserById(id);
        return ReturnResult.success("Ok");
    }
  
	@ApiOperation(value="后台登录用户的应用区域列表")
	@RequestMapping(value="/findAuthUserArea",method=RequestMethod.POST)
	public ReturnResult<String> findAuthUserArea(HttpServletRequest request){		
		List<CommDataConfig> dataList=new ArrayList<CommDataConfig>();	
		LoginRedisObj obj=this.getUserObj(request);		
		AuthUser authUser=authUserService.selectBaseByPrimaryKey(obj.getUserId());
		String areaIds=authUser.getAreaId();
		if(!StringUtils.isEmpty(areaIds)){
			String[] areaIdArr=areaIds.split(",");
			for(String id:areaIdArr){
				CommDataConfig data=commDataConfigService.selectByPrimaryKey(id);	
				dataList.add(data);
			}
		}		
		return ReturnResult.success(dataList);
	}
    
    
    
    
    
    
    
    
    
    
    
}
